#coding=utf-8

##---写字楼栏目首页------------------------------------
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.http import Http404
from job.models import Company, Job
from office.models import Office, OfficeAlbum
from pub.views import _app_page

_tmpl_index = "office/index.html"
_tmpl_office_detail = "office/detail.html"
model_url = "/office/" #为模板中的区域选择的链接拼接完整URL路径

def index(request, dist_id = None):
    '''
    写字楼首页渲染视图函数
    '''
    if dist_id is None:
        dist_id = -1
        query = Office.objects.filter(city=request.session["city"]).order_by("-id")
    else:
        query = Office.objects.filter(city=request.session["city"], district_id = dist_id).order_by("-id")
    paginator = Paginator(query, 10)
    if request.GET.get('page'):
        current_page = int(request.GET.get('page'))
    else:
        current_page = 1
    try:
        officeList = paginator.page(current_page)
    except PageNotAnInteger:
        # If page is not an integer, deliver first page.
        officeList = paginator.page(1)
    except EmptyPage:
        # If page is out of range (e.g. 9999), deliver last page of results.
        officeList = paginator.page(paginator.num_pages)
    local = dict(officeList=officeList, districts_select = int(dist_id), model_url=model_url)
    return _app_page(_tmpl_index, request, local)


def office_detail(request, office_id=None):
    """
        某写安楼的详细信息, office_id是写字楼的ID
        查询写字楼信息,相册等,楼内公司信息,楼周边商户等
    """
    if office_id is None:
        raise Http404
    try:
        office = Office.objects.get(id=office_id)
        officeAlbum = OfficeAlbum.objects.filter(office=office).order_by("create_date")
    except Exception:
        raise Http404
    #查找楼内公司
    companies = Company.objects.filter(office=office).order_by("create_date")
    companiesAndCounts = {}
    for company in companies:
        counts = Job.objects.filter(company=company).count()
        companiesAndCounts[company] = counts

    local = dict(office=office, companiesAndCounts=companiesAndCounts, officeAlbum=officeAlbum)
    return _app_page(_tmpl_office_detail, request, local)
